﻿using System;
using System.Diagnostics;

namespace Simp.Model
{
	/// <summary>Unbound calling expression:  parameters are the parameters to apply to the expression.</summary>
	[DebuggerDisplay("{ExpressionHelper.Serialize(this)}")]
	public class UnboundCallingExpression : IExpression, INamedExpression, IParameterPolicyExpression, IExpressionSerializer
	{
		private readonly string _name;
		private readonly IParameterBinding[] _parameterBindings;

		/// <summary>Constructor taking the unbound expression name and the number of parameters.</summary>
		/// <param name="name"></param>
		/// <param name="parameterCount"></param>
		public UnboundCallingExpression(string name, int parameterCount)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullException("name");
			}
			if (parameterCount < 0)
			{
				throw new ArgumentException("Can't be negative", "parameterCount");
			}
			_name = name;
			_parameterBindings = ExpressionHelper.CreateParameterBinding(parameterCount);
		}

		#region INamedExpression Members
		string INamedExpression.Name
		{
			get { return _name; }
		}
		#endregion

		#region IParameterPolicyExpression Members
		IParameterBinding[] IParameterPolicyExpression.ParameterBindings
		{
			get { return _parameterBindings; }
		}
		#endregion

		#region IExpressionSerializer Members
		void IExpressionSerializer.Serialize(AppendOnlyStringBuilder builder, params IExpression[] parameters)
		{
			if (builder == null)
			{
				throw new ArgumentNullException("builder");
			}
			if (parameters == null)
			{
				throw new ArgumentException("Wrong # of parameters", "parameters");
			}
			builder.Append("[");
			builder.Append(_name);
			builder.Append("]");
			if (parameters.Length > 0)
			{
				builder.Append("(");
				for (int i = 0; i != parameters.Length; ++i)
				{
					ExpressionHelper.Serialize(builder, parameters[i]);

					if (i != parameters.Length - 1)
					{
						builder.Append(", ");
					}
				}
				builder.Append(")");
			}
		}
		#endregion
	}
}